package com.hzhr.iot.cqgas.ds.service;

import com.hzhr.iot.core.constant.CommonOptions;
import com.hzhr.iot.core.util.HzhrDateUtil;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.cqgas.ds.dao.device.custom.DevCollectDataCustomDao;
import com.hzhr.iot.cqgas.ds.dao.device.example.DevCollectDeviceDao;
import com.hzhr.iot.cqgas.ds.dao.smartmeter.custom.SmGasUserCustomDao;
import com.hzhr.iot.cqgas.ds.dao.toll.custom.TollGasUserCustomDao;
import com.hzhr.iot.cqgas.ds.dao.toll.example.TollGasUserDao;
import com.hzhr.iot.cqgas.ds.dao.user.example.UsrDeptDao;
import com.hzhr.iot.cqgas.ds.entity.device.DevCollectDeviceExample;
import com.hzhr.iot.cqgas.ds.entity.toll.TollGasUserEntity;
import com.hzhr.iot.cqgas.ds.entity.toll.TollGasUserExample;
import com.hzhr.iot.cqgas.ds.entity.user.UsrDeptEntity;
import com.hzhr.iot.cqgas.ds.entity.user.UsrDeptExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class GasUserService {
    @Autowired
    TollGasUserDao tollGasUserDao;
    @Autowired
    SmGasUserCustomDao smGasUserCustomDao;
    @Autowired
    TollOptionsService tollOptionsService;
    @Autowired
    UsrDeptDao usrDeptDao;
    @Autowired
    DevCollectDataCustomDao devCollectDataCustomDao;
    @Autowired
    DevCollectDeviceDao devCollectDeviceDao;
    @Autowired
    TollGasUserCustomDao tollGasUserCustomDao;

    @Value("${companyId}")
    String companyId;

    private Logger logger = LoggerFactory.getLogger(GasUserService.class);

    public void syncGasUser(Date startDate, Date endDate) {
        int addCount = 0;
        int updateCount = 0;
        long start = new Date().getTime();

        Map<String, Object> criteriaMap = new HashMap<>();
        if (startDate != null) criteriaMap.put("startDate", HzhrDateUtil.dateToStr(startDate));
        if (endDate != null) criteriaMap.put("endDate", HzhrDateUtil.dateToStr(endDate));
        List<Map<String, Object>> gasUsers = smGasUserCustomDao.selectGasUser(criteriaMap);

        String resident = tollOptionsService.getCode("GAS_USER_TYPE", "RESIDENTIAL_USER");
        String commercial = tollOptionsService.getCode("GAS_USER_TYPE", "COMMERCIAL_USER");

        for (Map<String, Object> gasUser :
        gasUsers) {
            try {
                String yqdzId = HzhrTypeUtil.object2string(gasUser.get("YQDZ_ID"));
                String yqdzYqzh = HzhrTypeUtil.object2string(gasUser.get("YQDZ_YQZH"));
                String yqdzHzMc = HzhrTypeUtil.object2string(gasUser.get("YQDZ_HZ_MC"));
                String yqdzSm = HzhrTypeUtil.object2string(gasUser.get("YQDZ_SM"));
                String yqdzKhLx = HzhrTypeUtil.object2string(gasUser.get("YQDZ_KH_LX"));
                String orgId = HzhrTypeUtil.object2string(gasUser.get("ORG_ID"));

                //如果燃气用户由iot平台自建，则跳过
                TollGasUserExample tollGasUserExample = new TollGasUserExample();
                tollGasUserExample.createCriteria().andCodeEqualTo(yqdzYqzh).andOutIdIsNull().andIsValidEqualTo("1");
                int count = tollGasUserDao.countByExample(tollGasUserExample);
                if (count > 0) {
                    continue;
                }

                String deptCode = orgId.replace("0000", "9-01");
                String resourceCode = orgId.replace("0000", "01000901");

                tollGasUserExample = new TollGasUserExample();
                tollGasUserExample.createCriteria().andOutIdEqualTo(yqdzId);
                List<TollGasUserEntity> tollGasUserEntities = tollGasUserDao.selectByExample(tollGasUserExample);

                if (tollGasUserEntities.size() > 0) {
                    TollGasUserEntity tollGasUserEntity = tollGasUserEntities.get(0);
                    tollGasUserEntity.setOutId(yqdzId);
                    tollGasUserEntity.setName(yqdzHzMc != null ? yqdzHzMc : "未知");
                    tollGasUserEntity.setName(yqdzHzMc);
                    tollGasUserEntity.setAddress(yqdzSm);
                    if ("1".equals(yqdzKhLx)) {
                        tollGasUserEntity.setTypeCode(commercial);
                    } else if ("2".equals(yqdzKhLx)) {
                        tollGasUserEntity.setTypeCode(resident);
                    } else {
                        tollGasUserEntity.setTypeCode("0");
                    }
                    tollGasUserEntity.setCompanyId(Integer.parseInt(companyId));

                    UsrDeptExample usrDeptExample = new UsrDeptExample();
                    usrDeptExample.createCriteria().andCodeEqualTo(deptCode);
                    List<UsrDeptEntity> usrDeptEntities = usrDeptDao.selectByExample(usrDeptExample);
                    if (usrDeptEntities.size() > 0) {
                        UsrDeptEntity usrDeptEntity = usrDeptEntities.get(0);
                        tollGasUserEntity.setDeptId(usrDeptEntity.getId());
                    } else {
                        tollGasUserEntity.setDeptId(0);
                    }

                    tollGasUserEntity.setUpdateTime(new Date());
                    tollGasUserEntity.setUpdateUserId(0);
                    tollGasUserEntity.setResourceCode(resourceCode);
                    tollGasUserEntity.setIsValid(CommonOptions.YES_NO.YES);
                    tollGasUserEntity.setState("1");
                    tollGasUserDao.updateByPrimaryKey(tollGasUserEntity);
                    updateCount++;
                } else {
                    TollGasUserEntity tollGasUserEntity = new TollGasUserEntity();
                    tollGasUserEntity.setOutId(yqdzId);
                    tollGasUserEntity.setCode(yqdzYqzh);
                    tollGasUserEntity.setName(yqdzHzMc != null ? yqdzHzMc : "未知");
                    tollGasUserEntity.setAddress(yqdzSm);
                    if ("1".equals(yqdzKhLx)) {
                        tollGasUserEntity.setTypeCode(commercial);
                    } else if ("2".equals(yqdzKhLx)) {
                        tollGasUserEntity.setTypeCode(resident);
                    } else {
                        tollGasUserEntity.setTypeCode("0");
                    }
                    tollGasUserEntity.setCompanyId(Integer.parseInt(companyId));

                    UsrDeptExample usrDeptExample = new UsrDeptExample();
                    usrDeptExample.createCriteria().andCodeEqualTo(deptCode);
                    List<UsrDeptEntity> usrDeptEntities = usrDeptDao.selectByExample(usrDeptExample);
                    if (usrDeptEntities.size() > 0) {
                        UsrDeptEntity usrDeptEntity = usrDeptEntities.get(0);
                        tollGasUserEntity.setDeptId(usrDeptEntity.getId());
                    } else {
                        tollGasUserEntity.setDeptId(0);
                    }

                    tollGasUserEntity.setCreateTime(new Date());
                    tollGasUserEntity.setCreateUserId(0);
                    tollGasUserEntity.setResourceCode(resourceCode);
                    tollGasUserEntity.setIsValid(CommonOptions.YES_NO.YES);
                    tollGasUserEntity.setState("1");
                    tollGasUserDao.insert(tollGasUserEntity);
                    addCount++;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        long end = new Date().getTime();
        logger.info("同步燃气用户结束: " + (end - start) / 1000 + "s");
        logger.info("同步时间: " + (end - start) / 1000 + "s");
        logger.info("更新数量: " + updateCount + "条");
        logger.info("新增数量: " + addCount + "条");

    }

    public void syncGasUserGasConsumeAndDeviceCount() {
        int updateCount = 0;
        long start = new Date().getTime();

        List<TollGasUserEntity> tollGasUserEntities = tollGasUserDao.selectByExample(new TollGasUserExample());

        List<TollGasUserEntity> updateGasUsers = new ArrayList<>();
        for (TollGasUserEntity tollGasUserEntity :
                tollGasUserEntities) {
            try {
                Integer gasUserId = tollGasUserEntity.getId();

                //查询最近一条数据
                Double gasConsume = devCollectDataCustomDao.selectGasConsumeByGasUser(gasUserId);

                //查询设备数量
                DevCollectDeviceExample devCollectDeviceExample = new DevCollectDeviceExample();
                devCollectDeviceExample.createCriteria().andGasUserIdEqualTo(gasUserId);
                int collectDeviceCount = devCollectDeviceDao.countByExample(devCollectDeviceExample);

                tollGasUserEntity.setGasConsume(gasConsume);
                tollGasUserEntity.setCollectDeviceCount(collectDeviceCount);
                tollGasUserEntity.setUpdateUserId(0);
                tollGasUserEntity.setUpdateTime(new Date());

                updateGasUsers.add(tollGasUserEntity);
                updateCount++;
                if (updateGasUsers.size() == 1000) {
                    tollGasUserCustomDao.updateBatch(updateGasUsers);
                    updateGasUsers = new ArrayList<>();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (updateGasUsers.size() > 0) {
            tollGasUserCustomDao.updateBatch(updateGasUsers);
        }

        long end = new Date().getTime();
        logger.info("同步燃气用户用气量及设备数量结束: " + (end - start) / 1000 + "s");
        logger.info("同步时间: " + (end - start) / 1000 + "s");
        logger.info("更新数量: " + updateCount + "条");
    }
}
